// pages/api/user/[id].js
import {User} from '../../../db/models/user'
import {sendError, sendSuccess} from "../../utils/responseHandler";

export default async function handler(req, res) {
    const {id} = req.query;

    if (req.method === 'PUT') {
        // 更新用户数据
        try {
            const {username, email, nickname, work_position, year} = req.body;
            const user = await User.findByPk(id);  // 根据主键找到用户
            if (user) {
                user.username = username;
                user.email = email;
                user.nickname = nickname;
                user.work_position = work_position;
                user.year = year;
                await user.save();  // 保存更新
                sendSuccess(res, '1');
            } else {
                sendError(res, '用户未找到', 404);
            }
        } catch (error) {
            sendError(res, '更新失败', 500);
        }
    } else if (req.method === 'DELETE') {
        // 删除用户
        try {
            const user = await User.findByPk(id);
            if (user) {
                await user.destroy();  // 删除用户
                sendSuccess(res, '1');
            } else {
                sendError(res, '用户未找到', 404);
            }
        } catch (error) {
            sendError(res, '删除失败', 500);
        }
    } else {
        // 不支持其他方法
        res.setHeader('Allow', ['PUT', 'DELETE']);
        res.status(405).end(`Method ${req.method} Not Allowed`);
    }
}
